package com.kfm.jdbc.day0405;


/**
 * 写 5 个线程对 i 进行 100次 加一操作，再写 5 个线程对 i 进行100次 减一操作，输出结果
 */
public class Demo01 {
    public static void main(String[] args) {
        MyRunnablePlus myRunnablePlus = new MyRunnablePlus();
        MyRunnableMinus myRunnableMinus = new MyRunnableMinus();
        for (int i = 0; i < 5; i++) {
            new Thread(myRunnablePlus).start();
            new Thread(myRunnableMinus).start();
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println(MyRunnablePlus.i);
    }

}


class MyRunnablePlus implements Runnable{

    static int i = 0;

    @Override
    public void run() {
        for (int j = 0; j < 100; j++) {
            plus();
        }
    }

    public synchronized void plus() {
        i++;
    }

}

class MyRunnableMinus implements Runnable{

    @Override
    public void run() {
        for (int j = 0; j < 100; j++) {
            minus();
        }
    }

    public synchronized void minus() {
        MyRunnablePlus.i --;
    }

}